package com.apps.ftapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.viewpager.widget.ViewPager;

import com.apps.ftapp.R;
import com.apps.ftapp.adapter.TimeTableAdapter;
import com.apps.ftapp.bean.Lesson;
import com.apps.ftapp.model.TimeTableModel;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.DensityUtils;
import com.apps.ftapp.util.Tools;
import com.apps.ftapp.view.CustomDayView;
import com.google.gson.Gson;
import com.ldf.calendar.component.CalendarAttr;
import com.ldf.calendar.component.CalendarViewAdapter;
import com.ldf.calendar.interf.OnSelectDateListener;
import com.ldf.calendar.model.CalendarDate;
import com.ldf.calendar.view.Calendar;
import com.ldf.calendar.view.MonthPager;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cz.msebera.android.httpclient.Header;


public class TimeTableActivity extends BaseActivity {


    CoordinatorLayout content;
    MonthPager monthPager;
    private TextView tvYear;
    private TextView tvMonth;
    private TextView hint_text;
    private RelativeLayout list_rel;
    private TimeTableAdapter timeTableAdapter;
    private CalendarViewAdapter calendarViewAdapter;
    private OnSelectDateListener onSelectDateListener;
    private ArrayList<Calendar> currentCalendars = new ArrayList<>();
    private int mCurrentPage = MonthPager.CURRENT_DAY_INDEX;
    private CalendarDate currentDate;
    private boolean initiated = false;
    private Gson gson = new Gson();
    private ListView listView;

    //控件相关地址  https://github.com/MagicMashRoom/SuperCalendar
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time_table);
        tvYear = findViewById(R.id.year);
        tvMonth = findViewById(R.id.month);
        monthPager = findViewById(R.id.calendar_view);
        monthPager.setViewHeight(DensityUtils.dp2px(TimeTableActivity.this, 270));
        listView = findViewById(R.id.tlist);
        hint_text = findViewById(R.id.hint_text);
        list_rel = findViewById(R.id.list_rel);
        //这里用线性显示 类似于listview
        setTitle("课程日历");
        init();
    }

    private void init() {
        //初始化
        currentDate = new CalendarDate();
        tvYear.setText(currentDate.getYear() + " 年");
        tvMonth.setText(currentDate.getMonth() + " 月");
        initListener();
        getCourseList(String.valueOf(currentDate));

        CustomDayView customDayView = new CustomDayView(TimeTableActivity.this, R.layout.custom_day);
        calendarViewAdapter = new CalendarViewAdapter(TimeTableActivity.this, onSelectDateListener, CalendarAttr.CalendarType.MONTH,
                CalendarAttr.WeekArrayType.Monday, customDayView);

        List<Lesson> list = new ArrayList<>();
        timeTableAdapter = new TimeTableAdapter(this, R.layout.item_time_table, list);
        listView.setAdapter(timeTableAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Lesson lesson = (Lesson) adapterView.getAdapter().getItem(i);

                Intent intent = null;
                if (lesson.getType().equals("live")) {
                    intent = new Intent(getApplicationContext(), CustomizedLiveActivity.class);
                } else if (lesson.getType().equals("video")) {
                    intent = new Intent(getApplicationContext(), CusomizedPlayBackActivity.class);
                } else if (lesson.getType().equals("weikaike")) {
                    Toast.makeText(TimeTableActivity.this, "课程暂时未开课~", Toast.LENGTH_LONG).show();
                    return;
                }
                intent.putExtra("appKey", Constant.APPKEY);
                intent.putExtra("nickname", Tools.isNull(Constant.nickname).equals("") ? "未知用户" : Constant.nickname);
                intent.putExtra("partner", Constant.PID);
                intent.putExtra("roomId", lesson.getRoomId());
                intent.putExtra("uid", Constant.uid);
                intent.putExtra("title", lesson.getTitle());
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                getApplicationContext().startActivity(intent);
            }
        });
        initMarkData();
        initMonthPager();
    }

    private void initListener() {
        onSelectDateListener = new OnSelectDateListener() {
            @Override
            public void onSelectDate(CalendarDate calendarDate) {
                //点击触发的方法 这里触发
                String tempTime = String.valueOf(calendarDate);
                getCourseList(tempTime);

            }

            @Override
            public void onSelectOtherMonth(int i) {
                monthPager.selectOtherMonth(i);
            }
        };
    }

    private void initMarkData() {
        HashMap markData = new HashMap<>();
        //1表示红点，0表示灰点  //但是真实的数据时0红点 1灰点
        Intent intent = getIntent();
        String temp = intent.getStringExtra("data");
        if (!temp.equals("") && temp != null) {
            String[] list = temp.split(",");
            for (int i = 0; i < list.length; i++) {
                markData.put(list[i], "0");
            }
        }
        calendarViewAdapter.setMarkData(markData);
    }

    private void initMonthPager() {
        monthPager.setAdapter(calendarViewAdapter);
        monthPager.setCurrentItem(MonthPager.CURRENT_DAY_INDEX);
        monthPager.setPageTransformer(false, new ViewPager.PageTransformer() {
            @Override
            public void transformPage(View page, float position) {
                position = (float) Math.sqrt(1 - Math.abs(position));
                page.setAlpha(position);
            }
        });
        monthPager.addOnPageChangeListener(new MonthPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mCurrentPage = position;
                currentCalendars = calendarViewAdapter.getPagers();
                if (currentCalendars.get(position % currentCalendars.size()) != null) {
                    CalendarDate date = currentCalendars.get(position % currentCalendars.size()).getSeedDate();
                    currentDate = date;
                    tvYear.setText(date.getYear() + " 年");
                    tvMonth.setText(date.getMonth() + " 月");
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void getCourseList(String selectTime) {
        RequestParams params = new RequestParams();
        params.add("userId", Constant.uid);
        params.add("token", Constant.token);
        params.add("day", selectTime);
        Async.post("my/daycronlist", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    try {
                        TimeTableModel result = gson.fromJson(new String(responseBody), TimeTableModel.class);
                        if (1 == Tools.isIntNull(result.getSuccess())) {
                            timeTableAdapter.clear();
                            if (null != result.getLessons() && result.getLessons().size() > 0) {
                                listView.setVisibility(View.VISIBLE);
                                hint_text.setVisibility(View.GONE);
                                timeTableAdapter.addAll(result.getLessons());
                                timeTableAdapter.notifyDataSetChanged();
                            }
                        } else {
                            listView.setVisibility(View.GONE);
                            hint_text.setVisibility(View.VISIBLE);
                        }
                    } catch (Exception e) {

                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }
}
